package main

import (
	"bytes"
	"encoding/gob"
	"log"
	"time"

	"github.com/saint-yellow/go-pl/toys/sensor-simulator/calculation"
	"github.com/saint-yellow/go-pl/toys/sensor-simulator/models"
	"github.com/saint-yellow/go-pl/toys/sensor-simulator/tools"
	"github.com/streadway/amqp"
)

func main() {
	url := "amqp://guest:guest@localhost:5672"
	connection := tools.CreateConnection(url)
	channel := tools.CreateChannel(connection)
	
	defer connection.Close()
	defer channel.Close()
	
	queue := tools.CreateQueue(channel)
	sensorQueue := tools.CreateQueue(channel)
	sensorQueue.Name = tools.SensorListQueue

	buffer := new(bytes.Buffer)
	encoder := gob.NewEncoder(buffer)

	for range calculation.Signal {
		calculation.CalculateValue()

		reading := models.SensorMessage{
			Name: queue.Name,
			Value: calculation.Value,
			Timestamp: time.Now(),
		}
		buffer.Reset()
		encoder.Encode(reading)

		message := amqp.Publishing{
			Body: []byte(queue.Name),
		}

		channel.Publish("", sensorQueue.Name, false, false, message)

		log.Printf("读取到数据: %v\n", calculation.Value)
	}
}
